package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.EditTextLengthUtil;
import com.wdh.kjs.util.PhonenumUtil;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by CQH on 2016/4/21.
 */
public class ForgetPasswordActivity extends BaseTopActivity implements View.OnClickListener {
    private EditText updateLoginPassword_phone;
    private EditText updateLoginPassword_newpw;
    private EditText updateLoginPassword_renewpw;
    private EditText updateLoginPassword_inputmsg;
    private TimeCount time;
    private Button updateLoginPassword_getmsg;
    private Button updateLoginPassword_confirm;
    private Button updateLoginPassword_reinput;
    private JsonModel_my jsonModel_my;
    private Intent intent;
    private JsonModel jsonModel;

    private ImageView pwdView;
    private boolean pwdView_Visible=false;
    private ImageView repwdView;
    private boolean repwd_Visible=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xiugai);
        initTopBar("重置登录密码");
        time = new TimeCount(60000*3, 1000);
        initview();
    }


    private void loadData() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("phoneNumber", updateLoginPassword_phone.getText().toString());
        params.addBodyParameter("newpw", updateLoginPassword_newpw.getText().toString());
        params.addBodyParameter("verificationCode", updateLoginPassword_inputmsg.getText().toString());
        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.cookieStore);
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_FORGET_LOGINPW, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.getReturnMsg().equals("success")) {
                    trueDialogShow("密码重置已成功！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            intent = new Intent();
                            finish();
                            intent.setClass(ForgetPasswordActivity.this, LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    }, 2000);
                } else if (jsonModel_my.getReturnMsg().equals("nofind")) {
                    falseDialogShow("找不到用户！");
                } else if (jsonModel_my.getReturnMsg().equals("wrong")) {
                    falseDialogShow("密码重置失败！");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getBaseContext(), "网络异常！");
            }
        });

    }

    private void initview() {
        initTopBar("重置登录密码");
        updateLoginPassword_phone = (EditText) findViewById(R.id.updateLoginPassword_phone);
        updateLoginPassword_newpw = (EditText) findViewById(R.id.updateLoginPassword_newpw);
        updateLoginPassword_renewpw = (EditText) findViewById(R.id.updateLoginPassword_renewpw);
        updateLoginPassword_inputmsg = (EditText) findViewById(R.id.updateLoginPassword_inputmsg);
        updateLoginPassword_getmsg = (Button) findViewById(R.id.updateLoginPassword_getmsg);
        updateLoginPassword_confirm = (Button) findViewById(R.id.updateLoginPassword_confirm);
        updateLoginPassword_reinput = (Button) findViewById(R.id.updateLoginPassword_reinput);
        pwdView=(ImageView)findViewById(R.id.iv_newPwdVisible);
        repwdView=(ImageView)findViewById(R.id.iv_renewPwdVisible);

        updateLoginPassword_reinput.setOnClickListener(this);
        updateLoginPassword_confirm.setOnClickListener(this);
        updateLoginPassword_getmsg.setOnClickListener(this);
        pwdView.setOnClickListener(this);
        repwdView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String pwdPrompt = EditTextLengthUtil.check_numAndAlphabet(updateLoginPassword_newpw.getText().toString());
        switch (view.getId()) {
            case R.id.updateLoginPassword_getmsg:
                if (updateLoginPassword_phone.getText().toString().equals("")) {
                    falseDialogShow("请输入手机号！");
                } else if (!PhonenumUtil.isMobileNO(updateLoginPassword_phone.getText().toString())) {
                    falseDialogShow("请输入正确的手机号！");
                } else {
                    time.start();
                    intcode();
                }
                break;
            case R.id.updateLoginPassword_reinput:
                updateLoginPassword_phone.setText("");
                updateLoginPassword_newpw.setText("");
                updateLoginPassword_renewpw.setText("");
                updateLoginPassword_inputmsg.setText("");
                break;
            case R.id.updateLoginPassword_confirm:
                int newPwdLength = EditTextLengthUtil.check_length(updateLoginPassword_newpw.getText().toString());
                if (updateLoginPassword_phone.getText().toString().equals("")) {
                    falseDialogShow("请输入手机号！");
                } else if (!PhonenumUtil.isMobileNO(updateLoginPassword_phone.getText().toString())) {
                    falseDialogShow("请输入正确的手机号！");
                } else if (updateLoginPassword_newpw.getText().toString().equals("")) {
                    falseDialogShow("请输入新密码！");
                } else if (newPwdLength != 0) {
                    if (newPwdLength > 0) {
                        falseDialogShow("新密码位数多于" + EditTextLengthUtil.max_length + "位");
                    } else {
                        falseDialogShow("新密码位数少于" + EditTextLengthUtil.min_length + "位");
                    }
                }else if (pwdPrompt.length() > 0) {
                    falseDialogShow(pwdPrompt);
                }else if (updateLoginPassword_renewpw.getText().toString().equals("")) {
                    falseDialogShow("请输入确认密码！");
                } else if (!updateLoginPassword_newpw.getText().toString().equals(updateLoginPassword_renewpw.getText().toString())) {
                    falseDialogShow("新密码两次输入不一致！");
                } else {
                    loadData();
                }
                break;
            case R.id.iv_newPwdVisible:{
                int index=updateLoginPassword_newpw.getSelectionStart();
                pwdView_Visible = !pwdView_Visible;
                if (pwdView_Visible == true) {
                    //设置密码可见
                    updateLoginPassword_newpw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pwdView.setImageResource(R.drawable.visual);
                } else {//设置密码不可见
                    updateLoginPassword_newpw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pwdView.setImageResource(R.drawable.eye_icon);
                }
                updateLoginPassword_newpw.setSelection(index);
                break;
            }
            case R.id.iv_renewPwdVisible:{
                int index=updateLoginPassword_renewpw.getSelectionStart();
                repwd_Visible = !repwd_Visible;
                if (repwd_Visible == true) {
                    //设置密码可见
                    updateLoginPassword_renewpw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    repwdView.setImageResource(R.drawable.visual);
                } else {//设置密码不可见
                    updateLoginPassword_renewpw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    repwdView.setImageResource(R.drawable.eye_icon);
                }
                updateLoginPassword_renewpw.setSelection(index);
                break;
            }
            default:
                break;
        }
    }

    private void intcode() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("phoneNumber", updateLoginPassword_phone.getText().toString());
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_CODDING_Forget, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
//                    if (jsonModel.success) {
                DefaultHttpClient dh = (DefaultHttpClient) http.getHttpClient();
                MyCookieStore.cookieStore = dh.getCookieStore();

//                    }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(ForgetPasswordActivity.this, "网络异常！");
            }
        });


    }

    private void falseDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_false, null);
        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_negative.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
                updateLoginPassword_phone.setText("");
                updateLoginPassword_newpw.setText("");
                updateLoginPassword_renewpw.setText("");
                updateLoginPassword_inputmsg.setText("");
            }
        });
    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            updateLoginPassword_getmsg.setText("发送验证码");
            updateLoginPassword_getmsg.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            updateLoginPassword_getmsg.setClickable(false);//防止重复点击
            updateLoginPassword_getmsg.setText(millisUntilFinished / 1000 + "s后可重新获取");
        }
    }
}
